package com.xhs.main.service.yfb.impl;

import com.xhs.main.dao.yfb.YfbGroupMapper;
import com.xhs.main.entity.yfb.YfbGroup;
import com.xhs.main.entity.yfb.YfbGroupExample;
import com.xhs.main.service.rsb.RsbUserService;
import com.xhs.main.service.yfb.YfbGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @create 2020-10-20 10:40
 */
@Service
public class YfbGroupServiceImpl implements YfbGroupService {
    @Autowired
    YfbGroupMapper yfbGroupMapper;

    @Autowired
    RsbUserService rsbUserService;

    @Override
    public List<YfbGroup> allGroups() {
        YfbGroupExample example = new YfbGroupExample();
        return yfbGroupMapper.selectByExample(example);
    }

    @Override
    public List<YfbGroup> queryGroupByClass(String yfbRespClass) {

        YfbGroupExample example = new YfbGroupExample();
        YfbGroupExample.Criteria criteria = example.createCriteria();
        //模糊查询，通过分类查
        criteria.andYfbGroupClassEqualTo(yfbRespClass);
        //查父id不等于-1的
        criteria.andYfbGroupParentidNotEqualTo(-1);
        //查出来的是没有外壳的
        List<YfbGroup> yfbGroups = yfbGroupMapper.selectByExample(example);
        //将所有人的父id放到集合中
        List<Integer> id = new ArrayList<>();
        for (int i = 0; i < yfbGroups.size(); i++) {
            id.add(yfbGroups.get(i).getYfbGroupParentid());
        }
        //查主键和返回结果的父id相等的
        YfbGroupExample example2 = new YfbGroupExample();
        YfbGroupExample.Criteria criteria1 = example2.createCriteria();
        criteria1.andYfbGroupIdIn(id);
        List<YfbGroup> yfbGroups2 = yfbGroupMapper.selectByExample(example2);
        //将两个结果组合起来
        List<YfbGroup> groups = new ArrayList<>();
        groups.addAll(yfbGroups);
        groups.addAll(yfbGroups2);
        return groups;
    }

    @Override
    public void deleteGroupByParentId(Integer id) {
        yfbGroupMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void addGroup(YfbGroup yfbGroup) {
        YfbGroupExample example = new YfbGroupExample();
        YfbGroupExample.Criteria criteria = example.createCriteria();
        //根据组名查id
        criteria.andYfbGroupNameEqualTo(yfbGroup.getYfbGroupName());
        List<YfbGroup> yfbGroups = yfbGroupMapper.selectByExample(example);
        //将查询出来的数据，取第一个（其实只有一个），取主键，set进去父id中
        yfbGroup.setYfbGroupParentid(yfbGroups.get(0).getYfbGroupId());
        yfbGroupMapper.insert(yfbGroup);
    }

}
